package layouts;

import java.awt.*;
import java.util.HashMap;

public class PartialPercentLayout implements LayoutManager {
	protected HashMap<Component, Point> locations;
	protected boolean fill;
	
	public PartialPercentLayout() {
		locations = new HashMap<Component, Point>();
		fill = true;
	}
	
	@Override
	public void addLayoutComponent(String name, Component comp) {
		// Nothing to do
	}
    
	@Override
	public void layoutContainer(Container parent) {
		Component[] components = parent.getComponents();
		int parentWidth = parent.getWidth();
		int parentHeight = parent.getHeight();
		
		for(int i = 0; i < components.length; i++) {
			Component component = components[i];
			
			if(fill) {
				Point location = component.getLocation();
				
				if(location.getX() < 0)
					location.x = 0;
					
				if(location.getX() > 100)
					location.x = 100;
					
				if(location.getY() < 0)
					location.y = 0;
					
				if(location.getY() > 100)
					location.y = 100;
					
				locations.put(component, location);
			}
			
			int x = (int) ((parentWidth - component.getWidth()) * (locations.get(component).getX() / 100));
			int y = (int) ((parentHeight - component.getHeight()) * (locations.get(component).getY() / 100));
			
			component.setLocation(x, y);
		}
		
		fill = false;
	}
	
	@Override
	public Dimension minimumLayoutSize(Container parent) {
		Component[] components = parent.getComponents();
		Insets insets = parent.getInsets();
        int width = 0;
		int height = 0;
		
		for(int i = 0; i < components.length; i++) {
			Component component = components[i];
			int componentWidth = component.getWidth();
			int componentHeight = component.getHeight();
			int componentX = component.getX();
			int componentY = component.getY();
			
			if(componentX + componentWidth > width)
				width = componentX + componentWidth;
			
			if(componentY + componentHeight > height)
				height = componentY + componentHeight;
		}
		
        width += insets.left + insets.right;
		height += insets.top + insets.bottom;
		
		return new Dimension(width, height);
	}
	
    @Override
	public Dimension preferredLayoutSize(Container parent) {
		Component[] components = parent.getComponents();
		Insets insets = parent.getInsets();
        int width = 0;
		int height = 0;
		
		for(int i = 0; i < components.length; i++) {
			Component component = components[i];
			int componentWidth = component.getWidth();
			int componentHeight = component.getHeight();
			int componentX = component.getX();
			int componentY = component.getY();
			
			if(componentX + componentWidth > width)
				width = componentX + componentWidth;
			
			if(componentY + componentHeight > height)
				height = componentY + componentHeight;
		}
		
        width += insets.left + insets.right;
		height += insets.top + insets.bottom;
		
		return new Dimension(width, height);
	}
	
	@Override
	public void removeLayoutComponent(Component comp) {
		locations.remove(comp);
	}
}
